<?php
!defined('P_W') && exit('Forbidden');
class PW_House_VideoDB extends BaseDB {
	var $_tableName = "pw_house_video";
	var $_perpage = 14;
	
	function getVideos($hid,$page,$prePage) {
		$page = $this->_initPage($page);
		$temp = array();
		$rs = $this->_db->query('SELECT * FROM '.$this->_tableName.' WHERE hid='.pwEscape($hid).' ORDER BY id DESC'.pwLimit($page*$prePage,$prePage));
		while ($rt = $this->_db->fetch_array($rs)) {
			$temp[$rt['id']] = $rt;
		}
		return $temp;
	}
	
	function getAllByHid($hid) {
		$temp = array();
		$rs = $this->_db->query('SELECT * FROM '.$this->_tableName.' WHERE hid='.pwEscape($hid).' ORDER BY id DESC');
		while ($rt = $this->_db->fetch_array($rs)) {
			$temp[$rt['id']] = $rt;
		}
		return $temp;
	}
	
	function countByHid($hid) {
		return $this->_db->get_value('SELECT COUNT(*) as count FROM '.$this->_tableName.' WHERE hid='.pwEscape($hid));
	}
	
	function get($id) {
		return $this->_db->get_one('SELECT * FROM '.$this->_tableName.' WHERE id='.pwEscape($id) );
	}
	
	function insert($array) {
		$array	= $this->_checkData($array);
		if (!$array) return null;
		$this->_db->update('INSERT INTO '.$this->_tableName.' SET '.pwSqlSingle($array,false));
		return $this->_db->insert_id();
	}
	function update($id,$array){
		$array	= $this->_checkData($array);
		if (!$array) return null;
		$this->_db->update('UPDATE '.$this->_tableName.' SET '.pwSqlSingle($array,false).' WHERE id='.pwEscape($id));
	}
	function delete($id) {
		$this->_db->update('DELETE FROM '.$this->_tableName.' WHERE id='.pwEscape($id));
	}
	
	function getStruct() {
		return array('id','hid','address','image','uploadtime','descrip','ifembed','creator');
	}
	
	function _initPage($page) {
		return (int)$page>1 ? (int)$page -1 : 0;
	}

	function _checkData($data){
		if (!is_array($data) || !count($data)) return null;		
		$data = $this->_checkAllowField($data,$this->getStruct());
		if ($this->_checkLength($data,array('descrip'=>'255')) || !$data['address'] || strpos($data['address'],'<script')!==false) {
			return null;
		}
		if ($data['address'] && strpos($data['address'],'<embed') !==false) {
			$data['ifembed'] = 1;
		} else {
			$data['ifembed'] = 0;
		}
		return $data;
	}
	
	function _checkLength($data,$rule) {
		foreach ($rule as $key=>$value) {
			if ($data[$key] && strlen($data[$key])>$rule) {
				return true;
			}
		}
		return false;
	}
}
?>